const watermark = {
    mounted(el, binding) {
        const { text, font, color, fontSize, rotate, opacity } = binding.value;

        // 创建水印画布
        const canvas = document.createElement("canvas");
        canvas.width = 200;
        canvas.height = 150;

        const ctx = canvas.getContext("2d");
        if (ctx) {
            ctx.font = `${fontSize}px ${font}`;
            ctx.fillStyle = color;
            ctx.globalAlpha = opacity;
            ctx.rotate((-rotate * Math.PI) / 180);
            ctx.fillText(text, canvas.width / 10, canvas.height / 2);
        }

        // 将画布内容转换为 base64 编码的图片
        const base64Url = canvas.toDataURL();

        // 创建水印样式
        const watermarkStyle = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-image: url('${base64Url}');
      background-repeat: repeat;
      pointer-events: none;
    `;

        // 创建水印元素
        const watermarkElement = document.createElement("div");
        watermarkElement.style.cssText = watermarkStyle;

        // 设置元素的定位为相对定位，以便水印元素可以相对于它定位
        el.style.position = "relative";

        // 将水印元素添加到目标元素中
        el.appendChild(watermarkElement);
    },
    updated(el, binding) {
        // 当指令绑定的值更新时，重新生成水印
        const watermarkElement = el.querySelector("div");
        if (watermarkElement) {
            el.removeChild(watermarkElement);
        }

        const { text, font, color, fontSize, rotate, opacity } = binding.value;

        const canvas = document.createElement("canvas");
        canvas.width = 200;
        canvas.height = 150;

        const ctx = canvas.getContext("2d");
        if (ctx) {
            ctx.font = `${fontSize}px ${font}`;
            ctx.fillStyle = color;
            ctx.globalAlpha = opacity;
            ctx.rotate((-rotate * Math.PI) / 180);
            ctx.fillText(text, canvas.width / 10, canvas.height / 2);
        }

        const base64Url = canvas.toDataURL();

        const watermarkStyle = `
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-image: url('${base64Url}');
      background-repeat: repeat;
      pointer-events: none;
    `;

        const newWatermarkElement = document.createElement("div");
        newWatermarkElement.style.cssText = watermarkStyle;

        el.style.position = "relative";
        el.appendChild(newWatermarkElement);
    },
};

export default (app) => {
	app.directive("watermark", watermark);
};
